package com.haibei.activity.user;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.net.NetResult;
import com.common.task.BaseTask;
import com.common.task.NetCallBack;
import com.common.uitl.AssertTool;
import com.common.uitl.DrawTool;
import com.common.uitl.ListUtiles;
import com.common.uitl.LogUtil;
import com.common.uitl.StringUtils;
import com.common.uitl.Tool;
import com.haibei.App;
import com.haibei.R;
import com.haibei.activity.BaseHaibeiActivity;
import com.haibei.adapter.AnimationAdapter;
import com.haibei.adapter.bean.City;
import com.haibei.adapter.bean.User;
import com.haibei.net.NetInterface;
import com.haibei.view.LocationWheelView;
import com.haibei.view.StageWheelView;
import com.haibei.view.StageWheelView.StageSelectListener;

public class RegistActivity2 extends BaseHaibeiActivity implements View.OnClickListener {

	private View viewStageSelect;
	private View viewCitySelect;
	private ImageView imageViewHeader;
	private String mStringSex = "";
	private String mStringStage = "";
	private String mStringCity = "";
	private String mStringCityId="";
	
	private TextView mTextViewState;
	private TextView mTextViewCity;
	private BaseTask mBaseTask;
	private RadioGroup mRadioGroupSex;

	private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/Camera");
	private static File mCurrentPhotoFile;// 照相机拍照得到的图片

	private final int int_go_select_pic_gallery = 1000;
	private final int int_go_select_pic_camera = 1001;
	private final int int_go_select_crop = 1003;
	private File tempf = null;
	private Bitmap bitmap = null;
	private String mStringHeaderFilePath = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initView();
	}

	@Override
	public void initView() {
		setContentView(R.layout.activity_regist2);
		imageViewHeader=findImageViewById(R.id.imageViewHeader);
		mTextViewCity = findTextViewById(R.id.textViewCity);
		mRadioGroupSex = (RadioGroup) findViewById(R.id.radioGroupSex);
		mRadioGroupSex.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				mStringSex = (String) (findViewById(checkedId).getTag());
				mStringStage = "";
				mTextViewState.setText("请选择");
			}
		});
		mTextViewState = findTextViewById(R.id.textViewStage);
		viewStageSelect = findViewById(R.id.linearLayoutStateSelect);
		viewStageSelect.setOnClickListener(this);
		viewCitySelect = findViewById(R.id.linearLayoutCitySelect);
		viewCitySelect.setOnClickListener(this);
		findButtonById(R.id.buttonComplete).setOnClickListener(this);
		findButtonById(R.id.buttonCancell).setOnClickListener(this);
		findViewById(R.id.linearLayoutIconImage).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		switch (vid) {
		case R.id.linearLayoutIconImage: {
			showPicDialogSelect();
		}
			break;
		case R.id.linearLayoutStateSelect: {
			RelativeLayout rl = findRelativeLayout(R.id.relativelayoutWheels);
			StageWheelView swv = new StageWheelView(this, ("1".equals(mStringSex) ? true : false));
			swv.setSelectListener(new StageSelectListener() {
				@Override
				public void onSelect(String value, String text, String netValue) {
					mTextViewState.setText(value);
					mStringStage = netValue;
				}
			});
			rl.removeAllViews();
			rl.addView(swv);
			swv.show();
		}
			break;
		case R.id.buttonComplete:
			regist();
			break;
		case R.id.linearLayoutCitySelect: {
			showLocationProvince();
		}
			break;
		case R.id.buttonCancell: {
			finish();
		}
		default:
			break;
		}
	}

	// 照片选择
	private void showPicDialogSelect() {
		RelativeLayout rl = findRelativeLayout(R.id.relativelayoutWheels);
		rl.removeAllViews();
		final View view = View.inflate(RegistActivity2.this, R.layout.alert_dialog, null);
		final Animation slideBottomOut = AnimationUtils.loadAnimation(RegistActivity2.this, R.anim.slide_bottom_out);
		final Animation slideBottomIn = AnimationUtils.loadAnimation(RegistActivity2.this, R.anim.slide_bottom_in);
		slideBottomIn.setAnimationListener(new AnimationAdapter() {
			@Override
			public void onAnimationStart(Animation animation) {
				view.setVisibility(View.VISIBLE);
			}
		});

		slideBottomOut.setAnimationListener(new AnimationAdapter() {
			@Override
			public void onAnimationEnd(Animation animation) {
				view.setVisibility(View.GONE);
			}
		});

		View.OnClickListener clickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.btn_pick_photo: {
					doChosePic();
				}
					break;
				case R.id.btn_take_photo: {
					doTakePhoto();
				}
					break;
				case R.id.btn_cancel: {
				}
					break;
				}
				view.startAnimation(slideBottomOut);
			}
		};

		rl.addView(view);
		view.startAnimation(slideBottomIn);

		Button btnAlbulm = (Button) view.findViewById(R.id.btn_pick_photo);
		btnAlbulm.setOnClickListener(clickListener);

		Button btnPhoto = (Button) view.findViewById(R.id.btn_take_photo);
		btnPhoto.setOnClickListener(clickListener);

		Button btnCancell = (Button) view.findViewById(R.id.btn_cancel);
		btnCancell.setOnClickListener(clickListener);
	}

	protected void doChosePic() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, int_go_select_pic_gallery);
	}

	protected void doTakePhoto() {
		try {
			PHOTO_DIR.mkdirs();// 创建照片的存储目录
			mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, int_go_select_pic_camera);
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(App.tag, "创建文件失败......");
		}
	}

	private String getPhotoFileName() {
		return System.currentTimeMillis() + ".jpg";
	}

	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	private void showLocationProvince() {
		if (ListUtiles.isEmpty(App.mArrayListFirstLevelCity)) {
			ParseCityTask ptask = new ParseCityTask();
			ptask.execute();
		} else {
			RelativeLayout rl = findRelativeLayout(R.id.relativelayoutWheels);
			LocationWheelView swv = new LocationWheelView(this, App.mArrayListFirstLevelCity);
			swv.setSelectListener(new LocationWheelView.StageSelectListener() {
				@Override
				public void onSelect(City city) {
					mTextViewCity.setText(city.getName());
					mStringCity = city.getName();
					mStringCityId=city.getId();
				}
			});
			rl.removeAllViews();
			rl.addView(swv.getContentView());
			swv.show();
		}
	}

	private void regist() {
		if (StringUtils.isEmpty(mStringSex)) {
			Tool.ToastShow(this, "请选择性别！");
			return;
		}
		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("username", RegistActivity1.email);
		hmap.put("nikename", RegistActivity1.userName);
		hmap.put("password", RegistActivity1.password);
		hmap.put("sex", mStringSex);
		if (!StringUtils.isEmpty(mStringStage)) {
			hmap.put("stage", mStringStage);
		}
		if (!StringUtils.isEmpty(mStringCityId)) {
			hmap.put("address", mStringCityId);
		}
		getRegitTask().execute(hmap);
	}

	private BaseTask getRegitTask() {
		// 请求注册
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {

			@Override
			public void onPreCall() {
				super.onPreCall();
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						User u = (User) result.getData()[0];
						App.getApp().setUser(u);
						Tool.ToastShow(RegistActivity2.this, "注册成功！");
						setResult(RESULT_OK);
						finish();
					} else {
						Tool.ToastShow(RegistActivity2.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(RegistActivity2.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.regist(RegistActivity2.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});

		return mBaseTask;
	}

	@Override
	public void backFinish() {
		super.backFinish();
	}

	class ParseCityTask extends AsyncTask<Void, Void, ArrayList<City>> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showProgressDialog();
			App.mArrayListFirstLevelCity.clear();
		}

		@Override
		protected ArrayList<City> doInBackground(Void... params) {
			String citys = AssertTool.getStrFromAssert(RegistActivity2.this, "data/city.json");
			if (!StringUtils.isEmpty(citys)) {
				try {
					JSONArray jsa = new JSONArray(citys);
					for (int i = 0, isize = jsa.length(); i < isize; i++) {
						JSONObject jso = jsa.getJSONObject(i);// 一级城市
						String id = jso.getString("id");
						String name = jso.getString("name");
						City city = new City();
						city.setId(id);
						city.setName(name);
						if (jso.has("sub")) {// 添加子城市
							JSONArray subs = jso.getJSONArray("sub");
							for (int x = 0, xsize = subs.length(); x < xsize; x++) {
								JSONObject jsoSub = subs.getJSONObject(x);
								String subId = jsoSub.getString("id");
								String subName = jsoSub.getString("name");
								City subCity = new City();
								subCity.setId(subId);
								subCity.setName(subName);
								App.cityMap.put(subName, subCity);// 留待后用
								city.addSubCity(subCity);
							}
						}
						App.mArrayListFirstLevelCity.add(city);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(ArrayList<City> result) {
			super.onPostExecute(result);
			hideProgressDialog();
			showLocationProvince();
		}
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri, File outputFile) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		if (null != outputFile) {
			intent.putExtra("outputFormat", "JPEG");// 返回格式
			intent.putExtra("output", Uri.fromFile(outputFile));
		}
		startActivityForResult(intent, int_go_select_crop);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case int_go_select_pic_gallery:// 照片选择
		{
			startPhotoZoom(data.getData(), null);
		}
			break;
		case int_go_select_pic_camera:// 拍照
		{
			Uri imgUri = Uri.fromFile(mCurrentPhotoFile);
			tempf = new File(PHOTO_DIR, "x" + getPhotoFileName());// 给新照的照片文件命名
			startPhotoZoom(imgUri, tempf);
		}
			break;
		case int_go_select_crop:// 图片裁剪结果
			if (null != tempf) {// 照相获得照片
				mStringHeaderFilePath = tempf.getAbsolutePath();
				bitmap = BitmapFactory.decodeFile(mStringHeaderFilePath);
				// imageViewHeader.setImageBitmap(bitmap);
				imageViewHeader.setImageBitmap(DrawTool.toRoundCorner(bitmap, 15));
			} else {// 相册选择照片
				Uri uri = Uri.parse(data.getAction());
				Cursor cursor = this.getContentResolver().query(uri, null, null, null, null);
				cursor.moveToFirst();
				mStringHeaderFilePath = cursor.getString(1);
				bitmap = BitmapFactory.decodeFile(mStringHeaderFilePath);
				// imageViewHeader.setImageBitmap(bitmap);
				
				imageViewHeader.setImageBitmap(DrawTool.toRoundCorner(bitmap, 15));
			}
			break;
		}

	}
}
